<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.id?$t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="660px" top="5vh" @close='close'>
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :model="record" label-width="100px" :rules="rules" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('策略名称')" prop="name">
          <el-input v-emoji v-model="record.name" ref="name" style="width:300px;" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('描述')" prop="desc">
          <el-input v-emoji v-model="record.desc" ref="desc" style="width:300px;" :autosize="{ minRows: 4 }" type="textarea" @keydown.native="handleKeyCode($event)"></el-input>
        </el-form-item>
        <div style="margin-top:20px" class="avScrollbar">
          <el-table size='mini' ref="multipleTable" :data="record.rule_map">
            <el-table-column prop="switch" align='center' :label="$t('开关')" width="100">
              <template slot-scope="scope">
                <el-switch :width="45" v-model="scope.row.switch" class="switchs switch" active-color="#009966" inactive-color="#CCCCCC" active-value="enable" inactive-value="disable" :active-text="$t('开')" :inactive-text="$t('关')">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="proto" align='center' :label="$t('协议名称')" width="150">
            </el-table-column>
            <el-table-column prop="dir" align='center' :label="$t('方向')" width="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.dir" size='mini' @change="updateTable()" :ref="'dir' + (scope.$index + 1)" :disabled='protoList.includes(scope.row.proto)'>
                  <el-option v-for="item in dirTypeList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="action" align="center" :label="$t('动作')" width="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.action" size='mini' @change='updateTable' :ref="'action' + (scope.$index + 1)">
                  <el-option v-for="item in actionTypeList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addAv, editAv } from '@/api/safe/av'
import { inputClass, texttextClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'AvDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入策略名称')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      record: {
        id: null,
        name: '',
        desc: '',
        rule_map: [
          { action: 'alert', dir: 'upload', proto: 'http', switch: 'disable' },
          { action: 'alert', dir: 'upload', proto: 'smtp', switch: 'disable' },
          { action: 'alert', dir: 'download', proto: 'pop3', switch: 'disable' },
          { action: 'alert', dir: 'upload', proto: 'im', switch: 'disable' },
          { action: 'alert', dir: 'upload', proto: 'ftp', switch: 'disable' },
          { action: 'alert', dir: 'upload', proto: 's7_300', switch: 'disable' }
        ]
      },
      protoList: ['smtp', 'pop3'],
      recordCopy: {
        id: null,
        name: '',
        desc: '',
        rule_map: [
          { action: 'alert', dir: 'upload', proto: 'http', switch: 'disable' },
          { action: 'alert', dir: 'upload', proto: 'smtp', switch: 'disable' },
          { action: 'alert', dir: 'download', proto: 'pop3', switch: 'disable' },
          { action: 'alert', dir: 'upload', proto: 'im', switch: 'disable' },
          { action: 'alert', dir: 'upload', proto: 'ftp', switch: 'disable' },
          { action: 'alert', dir: 'upload', proto: 's7_300', switch: 'disable' }
        ]
      },
      actionTypeList: [ //   alert/deny  告警/阻断
        { value: 'alert', label: this.$t('告警') },
        { value: 'deny', label: this.$t('阻断') }
      ],
      dirTypeList: [
        { value: 'upload', label: this.$t('上传') },
        { value: 'both', label: this.$t('双向') },
        { value: 'download', label: this.$t('下载') }
      ],
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  watch: {
    'record.desc': {
      handler (newVal) {
        this.record.desc = newVal.replace(/[\r\n]/g, '')
      },
      immediate: true
    }
  },
  // mounted () {
  //   this.$nextTick(() => {
  //     // console.log(this.$refs[`dir${(scope.$index + 1)}`].$refs.reference.$refs.input)
  //     for (let i = 0; i < this.record.rule_map.length; i++) {
  //       this.$refs.dir.$refs.reference.$refs.input.classList.value += ' `dir[i]`'
  //       const selectData = ['dir', 'action']
  //       selectClass(this.$refs, selectData)
  //     }
  //   })
  // },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['name']
        const textdata = ['desc']
        inputClass(this.$refs, data)
        texttextClass(this.$refs, textdata)
        if (this.record.rule_map && this.record.rule_map.length > 0) {
          this.record.rule_map.forEach((item, index) => {
            const selectData = ['dir' + (index + 1), 'action' + (index + 1)]
            selectClass(this.$refs, selectData)
          })
        }
      })
      if (data) {
        this.record = JSON.parse(JSON.stringify(data))
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var formData = JSON.parse(JSON.stringify(this.record))
          formData.rule_map = JSON.stringify(formData.rule_map)
          if (this.record.id) {
            editAv(formData).then(res => {
              if (res.status === 0) {
                this.$message({
                  message: this.$t('编辑成功'),
                  type: 'success'
                })
                this.close()
                this.$parent.listData()
              }
            })
          } else {
            addAv(formData).then(res => {
              if (res.status === 0) {
                this.$message({
                  message: this.$t('添加成功'),
                  type: 'success'
                })
                this.close()
                this.$parent.listData()
              }
            })
          }
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.ruleAllList = []
      this.record = JSON.parse(JSON.stringify(this.recordCopy))
      this.$refs.multipleTable.clearSelection()
      this.$refs.form.resetFields()
    },
    updateTable () {
      var updata = this.record.rule_map
      this.record.rule_map = []
      for (let item of updata) {
        this.record.rule_map.push(item)
      }
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    }
  }
}
</script>
